package jwt

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/fatih/structs"
	"time"
	"vueBasic/global"
)

type JWT struct {
	SigningKey []byte
	Exp        int64
	Iss        string
	Aud        string
}

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

func NewJWT(app string) *JWT {
	if app == "admin" {
		jwtConfig := global.CONF.AdminJwt
		return &JWT{
			SigningKey: []byte(jwtConfig.SigningKey),
			Exp:        jwtConfig.ExpiresTime,
			Iss:        jwtConfig.Issuer,
			Aud:        jwtConfig.Aud,
		}
	} else {
		return &JWT{
			SigningKey: []byte("test"),
			Exp:        86400,
			Iss:        "test.tdi",
			Aud:        "test.tda",
		}
	}
}

// 创建一个token
func (j *JWT) CreateToken(data interface{}) (string, error) {
	claims := jwt.MapClaims{
		"exp": time.Now().Unix() + j.Exp, // 过期时间，必须设置,
		"iat": time.Now().Unix(),
		"iss": j.Iss,
		"aud": j.Aud,
	}
	info := structs.Map(data)
	for key, val := range info {
		claims[key] = val
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signingString, err := token.SignedString(j.SigningKey)
	if err != nil {
		global.LOG.Error("token创建失败", err)
		return "", err
	}
	return signingString, nil
}

// 解析 token
func (j *JWT) ParseToken(tokenString string) (jwt.Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, jwt.MapClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil && token.Valid {
		return token.Claims, nil
	} else {
		return nil, TokenInvalid
	}

}
